<?php

namespace Index\Controller;

use Think\Controller;

class BaseController extends Controller {

  var $userId, $userInfo,$shopConfig,$userMenu;
  var $menuSelectClass = 'active';
  var $notcheck = array('makecode,index');//不需要登陆就可调用

  public function __construct() {

    parent::__construct();
    /*if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') > 0 ) {
        header('location:'.U('Wap/Index/index'));
    }*/
    $this->checkLogin();
    if($this->userId > 0){
      $this->getAdminMenu();
      $this->header();
    }
    $sys_on = M("Sys")->where(array("name"=>"sys_on"))->getField("value");
    $sys_off = M("Sys")->where(array("name"=>"sys_off"))->getField("value");

    if($sys_on == 1)
    {
      header("Content-type: text/html; charset=utf-8");
      die($sys_off);
    }


    $this->loadConfig();
    $this->assign('m', MODULE_NAME);
    $this->assign('c', CONTROLLER_NAME);
    $this->assign('a', ACTION_NAME);

  }

  /**
   * 检测是否登录
   */
  public function checkLogin() {
    $userId = trim(session('userId'));
/*
    if (empty($userId) && !in_array(ACTION_NAME, $this->notcheck)) {
      $this->redirect('User/Index/login');
    }*/
    $userObj = D('User');
    $list = $userObj->userInfo(array('id' => $userId));
    $this->userId = $list['id'];
    $this->userInfo = $list;
    $this->assign('loginInfo', $this->userInfo);
  }

  /**
   * 获取后台菜单
   */
  private function getAdminMenu() {
    $this->userMenu = C('userMenu');
    foreach ($this->userMenu as $key => $item) {
      if(in_array($key,D('User')->userMenu[$this->userInfo['user_type']])){
        $this->userMenu[$key]['url'] = U($item['url']);
        if ($key == CONTROLLER_NAME . '_' . ACTION_NAME) {
          $this->userMenu[$key]['class'] = $this->menuSelectClass;
        }
      }else{
        unset($this->userMenu[$key]);
      }
    }
    $this->assign('menu', $this->userMenu);
    return $this->userMenu;
  }


  private function header() {
    $user = M("User");
    $userId = trim(session('userId'));
    $userinfo = $user->where("id=$userId")->select();
    $this->assign("userinfo",$userinfo);
  }
  /**
   * 批量处理路由
   */
  public function batchProcess() {
    $id = I("id");
    if(empty($id)){
      $this->error('请选择需要操作的信息.');
    }
    $batchAction = I("batch");
    $actionName = reset(array_keys($batchAction));
    if(method_exists($this,$actionName)){
      call_user_func(array($this,$actionName));
    }
  }
  
  private function loadConfig(){
    $shopConfigArray = C('shopConfig');
    foreach ($shopConfigArray as $key => $item) {
      $this->shopConfig[$key] = $item['value'];
    }
    $this->assign("shopConfig",$this->shopConfig);
    $this->assign("title",$this->shopConfig['shopName'].'用户登录');
  }

}
